package problem15;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//15.三数之和
//https://leetcode.cn/problems/3sum/

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        int n = nums.length;
        Arrays.sort(nums);
        List<List<Integer>> ret = new ArrayList<>();

        for(int i = 0; i<n;) {
            while(i > 0 && i<n-2 && nums[i] == nums[i-1]) {
                i++;
            }
            int target = -nums[i];
            int l = i+1, r = n-1;
            while(l < r) {
                if(nums[l] + nums[r] == target) {
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[i]);
                    list.add(nums[l]);
                    list.add(nums[r]);
                    ret.add(list);
                    l++;
                    r--;
                    while(l<n && nums[l] == nums[l-1]) {
                        l++;
                    }
                    while(r>0 && nums[r] == nums[r+1]) {
                        r--;
                    }
                }else if(nums[l] + nums[r] > target) {
                    r--;
                }else {
                    l++;
                }
            }
            i++;
        }

        return ret;
    }
}

/*
a + b + c = 0;
b + c = -a

*/